console.log('服务器正在打开');
var WebSoketServer = require('ws').Server,
    wss = new WebSoketServer({ port: 10087 });
let clients = [];
let clientsNameList = [];
console.log('服务器端口号为10087');
wss.on('connection', function (ws, req) {
    ws.ipconfig = req.connection.remoteAddress;
    ws.uuid = +new Date();
    clients.push({
        "id": clients.length + 1,
        "ws": ws,
        "name": '神秘人',
        "ip": req.connection.remoteAddress,
        'length':0
    })
    ws.on('message', function (message) {
        let name = false;
        clients.forEach(function (v, i) {
            if (ws.uuid === v.ws.uuid) {
                name = v.name;
                if(v.length == 0){
                    name = message.split('-')[0];
                    v.name = name;
                    clientsNameList.push(name)
                }
                v.length++
            }
        })

        clients.forEach(function (v, i) {
            let isMy = req.connection.remoteAddress === v.ip?true:false;
            v.ws.send(JSON.stringify({ "name": name, "msg": message,"isMy":isMy,'clientsNameList':clientsNameList }));
        })
    })
    ws.on("close",function(close){
        console.log(close);
        console.log(clients.length)
        clients.forEach(function(v,i){
            console.log(v.ws.uuid,ws.uuid)
            if(v.ws.uuid === ws.uuid){
                clients.splice(i,1);
                clientsNameList.splice(i,1);
            }
        })
        console.log(clients.length)
        console.log(ws.uuid)
        console.log(ws.ipconfig)
    })
})
